package com.pshcp.common.filter;

import com.framework.common.config.CustomConf;
import com.framework.util.DateUtil;
import com.framework.util.JwtUtil;
import com.framework.thread.ReqComTool;
import com.framework.util.SystemUtil;
import com.pshcp.domain.model.Session;
import com.pshcp.service.SessionService;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.Calendar;

/**
 * @Description: TODO
 * @Author: xiaoche
 * @Date: 2022/8/4 14:06
 */
@Slf4j
@Component
public class VisitFilter implements Filter {

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    private CustomConf customConf;

    @Autowired
    private SessionService sessionService;


    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
    }

    @SneakyThrows
    @Override
    public void doFilter(ServletRequest request, ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        ReqComTool.buildPshcpTraceId();
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String token = jwtUtil.getToken(httpServletRequest);
        if (!StringUtils.isBlank(token)) {
            String sessionId = jwtUtil.getClaimValue(token, "id");
            if (!StringUtils.isBlank(sessionId)) {
                Session session = sessionService.findById(Long.parseLong(sessionId));
                if (session != null) {
                    Integer userType = session.getTerminal() == 0 ? 0 : 1;
                    ReqComTool.buildReqComDTO2Session(token, session.getId(), session.getTerminal(), userType, session.getUserId());
                    Calendar calendar = DateUtil.buildCalendar(session.getSessionRefreshTime(), customConf.getSessionLoginTimeType(), customConf.getSessionLoginTime());
                    ReqComTool.buildSessionStatus(session.getBizStatus() == 0 && calendar.getTime().getTime() - DateUtil.currDate().getTime() > 0 ? 0 : 1);
                    if (ReqComTool.getSessionStatus() == 0) {
                        Calendar sessionRefreshTimeCalendar = DateUtil.buildCalendar(DateUtil.currDate(), customConf.getSessionLoginTimeType(), customConf.getSessionLoginTime());
                        session.setSessionRefreshTime(sessionRefreshTimeCalendar.getTime());
                        sessionService.update(session);
                    }
                }
            }
        }
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
    }
}
